﻿using CommunityToolkit.Mvvm.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics;
using System.Reflection;
using System.Windows;
using TiaoTiaoCode.DesignLangTranstlateTool.ViewModels;
using TiaoTiaoCode.MultiLanguage;

namespace TiaoTiaoCode.DesignLangTranstlateTool
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            var process = RunningInstance();
            if (process != null)
            {
                Shutdown();
                return;
            }

            TiaoTiaoMultiLang.UseMultiLang();

            TiaoTiaoMultiLang.AddSupportLang("法语", "fr");

            RegisterType();

            base.OnStartup(e);
        }

        void RegisterType()
        {
            Ioc.Default.ConfigureServices(new ServiceCollection()
                .AddScoped<MainViewModel>()
                .BuildServiceProvider()
                );
        }

        /// <summary>
        /// 获取当前程序运行进程
        /// </summary>
        /// <returns></returns>
        static Process? RunningInstance()
        {
            var current = Process.GetCurrentProcess();
            var processes = Process.GetProcessesByName(current.ProcessName);

            foreach (var process in processes)
            {
                if (process.Id != current.Id)
                {
                    // 确保例程从EXE文件运行 
                    if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") != current.MainModule!.FileName)
                    {
                        return process;
                    }
                }
            }

            return null;
        }
    }
}
